﻿using DigitalHealth.PACS.ChatWebSocket.Context;
using DigitalHealth.PACS.ChatWebSocket.Services;
using DigitalHealth.PACS.Model;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;

namespace DigitalHealth.PACS.ChatWebSocket.Repositories.Imp
{

    internal class ChatUserRepository : IChatUserRepository
    {
        public ChatUserRepository(ChatContext chatContext)
        {
            ChatContext = chatContext;
        }

        public ChatContext ChatContext { get; set; }
        public bool ChatUserExists(string id)
        {
            return ChatContext.Users.Any(c => c.Id.ToString() == id);
        }

        public void Create(ChatUser user)
        {
            ChatContext.Users.Add(user);
            ChatContext.SaveChanges();
        }

        public void Delete(ChatUser user)
        {
            var chatMessages=ChatContext.ChatMessages.Where(c => c.SenderUser == user || c.ReceiverUser == user);
            ChatContext.ChatMessages.RemoveRange(chatMessages);
            ChatContext.Users.Remove(user);
            ChatContext.SaveChanges();
        }

        public ChatUser GetChatUserById(string id)
        {
            return ChatContext.Users.Where(u=>u.Id==new Guid(id)).FirstOrDefault();
        }

        public IEnumerable<ChatUser> GetChatUsers()
        {
            return ChatContext.Users.ToList();
        }

        public IEnumerable<ChatUser> GetChatUserByChatGroup(Organization chatGroup)
        {
            return ChatContext.ChatGroups.Find(chatGroup).users;
        }

        public ChatUser GetChatUserByUserNo(string userNo)
        {
            return ChatContext.Users.Where(u=>u.No== userNo).FirstOrDefault();
        }

        public void Update(ChatUser user)
        {
            ChatContext.Users.Update(user);
            ChatContext.SaveChanges();
        }
    }
}
